/*
 * Copyright 2010,2011 Michael Nitsche
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package de.mnit.basis.crypt.digest;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import de.mnit.basis.crypt.JavaBase64;
import de.mnit.basis.fehler.Fehler;

/**
 * @author Michael Nitsche
 * Erstellt: 2007-08-05
 */
public class JavaDigest {

	private final JAVA_DIGEST vg;
	private final MessageDigest md;


	public JavaDigest(JAVA_DIGEST vg) {
		Fehler.objekt.wenn_Null(vg);
		this.vg=vg;
		try {
			this.md=MessageDigest.getInstance(this.vg.javaName);
		}
		catch(NoSuchAlgorithmException e) {
			throw Fehler.weitergeben(e, "Ungültiger Algorithmus: "+vg.name()+" ("+vg.javaName+")");
		}
	}


	public static JavaDigest neu(JAVA_DIGEST vg) {
		return new JavaDigest(vg);
	}


	public byte[] berechnen(byte[] text) {
		Fehler.objekt.wenn_Null(text);
		byte[] hash=md.digest(text);
		md.reset();
		return hash;
	}

	public void plus(byte[] ba) {
		md.update(ba);
	}

	public void plus(byte b) {
		md.update(b);
	}

	public void plus(byte[] ba, int offset, int len) {
		md.update(ba, offset, len);
	}

	public byte[] berechnen() {
		byte[] hash=md.digest();
		md.reset();
		return hash;
	}

	public String toString() {
		return JavaBase64.verschluesseln(berechnen());
	}

}
